package com.nageoffer.jobtrain.projects.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nageoffer.jobtrain.common.web.exception.ClientException;
import com.nageoffer.jobtrain.projects.common.biz.user.UserContext;
import com.nageoffer.jobtrain.projects.common.constant.RedisCacheConstant;
import com.nageoffer.jobtrain.projects.common.enums.UserContestSubmitEnums;
import com.nageoffer.jobtrain.projects.dao.entity.ContestDO;
import com.nageoffer.jobtrain.projects.dao.entity.ContestRemindDO;
import com.nageoffer.jobtrain.projects.dao.entity.UserContestDO;
import com.nageoffer.jobtrain.projects.dao.mapper.ContestMapper;
import com.nageoffer.jobtrain.projects.dao.mapper.ContestRemindMapper;
import com.nageoffer.jobtrain.projects.dao.mapper.UserContestMapper;
import com.nageoffer.jobtrain.projects.dto.req.UserContestCancelEnrollReqDTO;
import com.nageoffer.jobtrain.projects.dto.req.UserContestEnrollReqDTO;
import com.nageoffer.jobtrain.projects.dto.resp.UserContestRespDTO;
import com.nageoffer.jobtrain.projects.service.UserContestService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 用户报名竞赛接口实现层
 * author：唐晨
 */
@Service
@RequiredArgsConstructor
public class UserContestServiceImpl extends ServiceImpl<UserContestMapper, UserContestDO> implements UserContestService {
    private final ContestMapper contestMapper;
    private final UserContestMapper userContestMapper;
    private final ContestRemindMapper contestRemindMapper;
    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public void createRemindContest(UserContestEnrollReqDTO requestParam) {
        LambdaQueryWrapper<ContestDO> contestQueryWrapper = Wrappers.lambdaQuery(ContestDO.class)
                .eq(ContestDO::getId, requestParam.getContestId())
                .eq(ContestDO::getStatus, 1)
                .eq(ContestDO::getDelFlag, 0);
        ContestDO contestDO = contestMapper.selectOne(contestQueryWrapper);
        if (contestDO == null) {
            throw new ClientException("暂无该竞赛基本信息，无法报名参加竞赛");
        }
        // 判断竞赛是否已经开赛
        if (contestDO.getBeginTime().before(new Date())) {
            throw new ClientException("该竞赛已经开赛，无法报名参加竞赛");
        }
        // 判断该竞赛用户是否已经报名了
        LambdaQueryWrapper<UserContestDO> userContestQueryWrapper = Wrappers.lambdaQuery(UserContestDO.class)
                .eq(UserContestDO::getPhoneNumber, UserContext.getUsername())
                .eq(UserContestDO::getContestId, requestParam.getContestId())
                .eq(UserContestDO::getDelFlag, 0);
        UserContestDO userContestDO = userContestMapper.selectOne(userContestQueryWrapper);
        if (userContestDO != null) {
            throw new ClientException("用户已经报名过该竞赛，禁止多次报名参赛");
        }
        userContestMapper.insert(UserContestDO.builder()
                .contestId(requestParam.getContestId())
                .phoneNumber(UserContext.getUsername())
                .build());
    }

    @Override
    public void cancelEnrollContest(UserContestCancelEnrollReqDTO requestParam) {
        LambdaQueryWrapper<ContestDO> contestQueryWrapper = Wrappers.lambdaQuery(ContestDO.class)
                .eq(ContestDO::getId, requestParam.getContestId())
                .eq(ContestDO::getStatus, 1)
                .eq(ContestDO::getDelFlag, 0);
        ContestDO contestDO = contestMapper.selectOne(contestQueryWrapper);
        if (contestDO == null) {
            throw new ClientException("暂无该竞赛基本信息，无法取消报名参加竞赛");
        }
        // 判断竞赛是否已经开赛
        if (contestDO.getBeginTime().before(new Date())) {
            throw new ClientException("该竞赛已经开赛，无法取消报名参加竞赛");
        }
        // 判断该竞赛用户是否已经报名了
        LambdaUpdateWrapper<UserContestDO> userContestUpdateWrapper = Wrappers.lambdaUpdate(UserContestDO.class)
                .eq(UserContestDO::getPhoneNumber, UserContext.getUsername())
                .eq(UserContestDO::getContestId, requestParam.getContestId())
                .set(UserContestDO::getDelFlag, 1);
        userContestMapper.update(userContestUpdateWrapper);
        // 获取该用户这个竞赛预约通知信息
        LambdaQueryWrapper<ContestRemindDO> contestRemindDOLambdaQueryWrapper = Wrappers.lambdaQuery(ContestRemindDO.class)
                .eq(ContestRemindDO::getPhoneNumber, UserContext.getUsername())
                .eq(ContestRemindDO::getContestId, requestParam.getContestId());
        ContestRemindDO contestRemindDO = contestRemindMapper.selectOne(contestRemindDOLambdaQueryWrapper);
        if (contestRemindDO == null) {
            // 此时说明，这个用户只报名了该竞赛，未预约，直接返回即可
            return;
        }
        // 此时代码预约了竞赛，直接删除预约信息、以及预约缓存信息
        contestRemindMapper.delete(contestRemindDOLambdaQueryWrapper);
        // 这里更新了用户预约提醒信息，通过删除缓存来保证数据库与缓存双写一致问题（缓存key:contestID:phoneNumber）
        stringRedisTemplate.delete(RedisCacheConstant.USER_CONTEST_REMIND_INFORMATION +
                requestParam.getContestId() + ":" + UserContext.getUsername());
    }

    @Override
    public List<UserContestRespDTO> listEnrollContest() {
        List<UserContestRespDTO> actualResult = userContestMapper.listEnrollContest(UserContext.getUsername());
        return actualResult;
    }

    @Override
    public IPage<UserContestRespDTO> pageListEnrollContest(Integer current, Integer size) {
        Page<UserContestRespDTO> page = new Page<>(current, size);
        List<UserContestRespDTO> actualResult = userContestMapper.pageListEnrollContest(UserContext.getUsername(), page);
        page.setRecords(actualResult);
        return page;
    }

    @Override
    public void finishContest(Long contestId) {
        LambdaUpdateWrapper<UserContestDO> updateWrapper = Wrappers.lambdaUpdate(UserContestDO.class)
                .eq(UserContestDO::getPhoneNumber, UserContext.getUsername())
                .eq(UserContestDO::getContestId, contestId)
                .eq(UserContestDO::getDelFlag, 0)
                .set(UserContestDO::getSubmitPapers, UserContestSubmitEnums.SUBMITTING.getType());
        userContestMapper.update(updateWrapper);
    }
}
